<script setup lang="ts">
import {reactive, ref} from "vue";
import type {Ref} from "vue";
import {useCounterStore} from "@/stores/counter";
import router from "@/router";
import type {LoginRequest} from "@/api/user";
import {userLogin} from "@/api/user";
import type {FormInstance, FormRules} from "element-plus";

const loginFrom: Ref<LoginRequest> = ref({
  username: "admin",
  password: "991202"
})
const loginFromRef = ref<FormInstance>()

function submitForm(loginFromRef: FormInstance | undefined): void {
  if (!loginFromRef) return
  loginFromRef.validate((valid) => {
    if (valid) {
      userLogin(loginFrom.value).then(res => {
        useCounterStore().setToken(res.data.body)
        useCounterStore().setUsername(loginFrom.value.username)
        router.push({
          path: '/'
        })
      })
    }
  })
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '' || value === null || value === undefined) {
    callback(new Error('请输入密码！'))
  } else if (value.length < 6) {
    callback(new Error("密码长度小于6！"))
  } else {
    callback()
  }
}

const loginRules = reactive<FormRules>({
  username: [
    {
      required: true,
      trigger: 'change',
      message: '请输入用户名！',
    }
  ],
  password: [
    {
      required: true,
      validator: validatePassword,
      trigger: 'change',
    }
  ]
})

</script>

<template>
  <div class="loginContainer">
    <el-form ref="loginFromRef" :model="loginFrom" :rules="loginRules" size="large" class="loginFrom">
      <h3 class="title">Login</h3>
      <el-form-item prop="username">
        <el-input v-model="loginFrom.username" placeholder="账号"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginFrom.password" type="password" placeholder="密码" show-password/>
      </el-form-item>
      <el-button type="primary" style="width: 100%; font-size: 15px" @click="submitForm(loginFromRef)">登录</el-button>
    </el-form>
  </div>
</template>

<style scoped>
.loginContainer {
  min-height: 100%;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;

  .loginFrom {
    position: relative;
    width: 400px;
    max-width: 100%;
    margin: 12% auto 0;
    overflow: hidden;
    text-align: center;

    .title {
      font-size: 26px;
      color: #eee;
      margin: 0 auto 30px auto;
      font-weight: bold;
    }
  }
}

</style>